/*
===============================================================================
 Name        : I2C_Wakeup_Master.c
 Author      : $(author)
 Version     :
 Copyright   : $(copyright)
 Description : main definition
===============================================================================
*/

#include <stdio.h>
#include "LPC8xx.h"
#include "i2c.h"
#include "syscon.h"
#include "swm.h"
#include "utilities.h"
#include "iocon.h"
#include "chip_setup.h"

extern void setup_debug_uart(void);


#define I2CBAUD 100000

float temperatureC;
 float humidityRH;

 unsigned char sndata1[8];
 unsigned char sndata2[6];
 unsigned int   SN1;
 unsigned int   SN2;

#define CHECKSUM_ERROR 0x04
 typedef enum {DISABLE = 0, ENABLE = !DISABLE} FunctionalState;


typedef enum{
  TRIG_T_MEASUREMENT_HM    = 0xE3, // command trig. temp meas. hold master
  TRIG_RH_MEASUREMENT_HM   = 0xE5, // command trig. humidity meas. hold master
  TRIG_T_MEASUREMENT_POLL  = 0xF3, // command trig. temp meas. no hold master
  TRIG_RH_MEASUREMENT_POLL = 0xF5, // command trig. humidity meas. no hold master
  USER_REG_W               = 0xE6, // command writing user register
  USER_REG_R               = 0xE7, // command reading user register
  SOFT_RESET               = 0xFE  // command soft reset
}SHT2xCommand;

typedef enum {
  SHT2x_RES_12_14BIT       = 0x00, // RH=12bit, T=14bit
  SHT2x_RES_8_12BIT        = 0x01, // RH= 8bit, T=12bit
  SHT2x_RES_10_13BIT       = 0x80, // RH=10bit, T=13bit
  SHT2x_RES_11_11BIT       = 0x81, // RH=11bit, T=11bit
  SHT2x_RES_MASK           = 0x81  // Mask for res. bits (7,0) in user reg.
} SHT2xResolution;

typedef enum {
  SHT2x_EOB_ON             = 0x40, // end of battery
  SHT2x_EOB_MASK           = 0x40, // Mask for EOB bit(6) in user reg.
} SHT2xEob;

typedef enum {
  SHT2x_HEATER_ON          = 0x04, // heater on
  SHT2x_HEATER_OFF         = 0x00, // heater off
  SHT2x_HEATER_MASK        = 0x04, // Mask for Heater bit(2) in user reg.
} SHT2xHeater;


typedef enum{
  HUMIDITY,
  TEMP
}SHT2xMeasureType;

typedef enum{
  I2C_ADR_W                = 128,   // sensor I2C address + write bit
  I2C_ADR_R                = 129    // sensor I2C address + read bit
}I2cHeader;

const char promptstring[] = "Choose a low power mode for the slave:\n\r0 for Sleep\n\r1 for Deep-sleep\n\r2 for Power-down\n\r";

static void delay_us(int time_us )
{
  int i,j;
  for( i=0;i<time_us;i++ )
  {
		for( j=0;j<11;j++ );//1us
  }
}
 /**
  * @file   Delay_Ms(²»¾«È·)
  * @brief  ºÁÃëÑÓÊ± time_ms ms
  * @param  time_ms ÑÓÊ±Ê±¼ä
  * @retval NO
  */
static void delay_ms(int time_ms)
{
	int i;
  for( i=0;i<time_ms;i++ )
  {
		delay_us(11000);
  }

}
void DELAY(int z)//延时zms
{
int x,y;
for(x = z;x > 0;x--)
for(y = 110;y > 0;y--);
}
/**
  * @file   SHT2X_IIC_WriteByte
  * @brief  ÏòSHT20Ð´Ò»×Ö½ÚÊý¾Ý
  * @param
	*          - SendByte: ´ýÐ´ÈëÊý¾Ý
	*          - WriteAddress: ´ýÐ´ÈëµØÖ·
  * @retval ·µ»ØÎª:=1³É¹¦Ð´Èë,=0Ê§°Ü
  */
FunctionalState SHT2X_IIC_WriteByte(unsigned char WriteAddress,unsigned char SendByte)
{
    if(!I2C_Start())return DISABLE;
    I2C_SendByte(0x80);
    if(!I2C_WaitAck()){I2C_Stop(); return DISABLE;}
    I2C_SendByte(WriteAddress);   /* ÉèÖÃµÍÆðÊ¼µØÖ· */
    I2C_WaitAck();
    I2C_SendByte(SendByte);
    I2C_WaitAck();
    I2C_Stop();
    return ENABLE;
}
 /**
  * @file   SHT2X_IIC_ReadByte
  * @brief  ´ÓSHT20¶ÁÈ¡Ò»´®Êý¾Ý
  * @param
	*					- pBuffer: ´æ·Å¶Á³öÊý¾Ý
	*     	  - length: ´ý¶Á³ö³¤¶È
	*         - ReadAddress: ´ý¶Á³öµØÖ·
  * @retval ·µ»ØÎª:=1³É¹¦¶ÁÈë,=0Ê§°Ü
  */
FunctionalState SHT2X_IIC_ReadByte(unsigned char ReadAddress,int length  ,unsigned char* pBuffer)
{
	  if(!I2C_Start())return DISABLE;
    I2C_SendByte(0x80); /* ÉèÖÃ¸ßÆðÊ¼µØÖ·+Æ÷¼þµØÖ· */
    if(!I2C_WaitAck())
		{I2C_Stop(); return DISABLE;}
    I2C_SendByte(ReadAddress);   /* ÉèÖÃµÍÆðÊ¼µØÖ· */
    I2C_WaitAck();
    I2C_Start();
    I2C_SendByte(0x81);
    I2C_WaitAck();
    while(length)
    {
			*pBuffer = I2C_ReceiveByte();
			if(length == 1)
			I2C_NoAck();
			else I2C_Ack();
			pBuffer++;
			length--;
    }
    I2C_Stop();
    return ENABLE;
}
 /**
  * @file   SHT2x_CheckCrc
  * @brief  calculates checksum for n bytes of data and compares it with expected
  * @param
	*					- data[]: µÈ´ý¼ìÑéµÄÊý¾Ý
	*     	  - startByte: ¿ªÊ¼Êý×éµÄ±êºÅ
	*         - nbrOfBytes: ¼ìÑé¸öÊý
	*         - checksum: ½ÓÊÕµ½µÄCRCÊý¾Ý
  * @retval ·µ»ØÎª:=1¼ì²â³É¹¦,=0¼ì²âÊ§°Ü
  */
FunctionalState SHT2x_CheckCrc(unsigned char data[],unsigned char startBytes,unsigned char number, unsigned char checksum)
{
	unsigned char bit=0;
	unsigned char crc = 0;
  unsigned char byteCtr;
  //calculates 8-Bit checksum with given polynomial
  for (byteCtr = startBytes; byteCtr < startBytes+number; ++byteCtr)
  { crc ^= (data[byteCtr]);
    for (bit = 8; bit > 0; --bit)
    { if (crc & 0x80) crc = (crc << 1) ^ 0x131;
      else crc = (crc << 1);
    }
  }
  if (crc ==checksum)
	return ENABLE;
  else
	return DISABLE;
}
 /**
  * @file   SHT2x_ReadUserRegister
  * @brief  reads the SHT2x user register
  * @param  no
  * @retval ·µ»Ø¶ÁÈ¡µ½µÄ²ÎÊýÖµ
  */
unsigned char SHT2x_ReadUserRegister(void)
{
	unsigned char data[1]={0};
  SHT2X_IIC_ReadByte( USER_REG_R, 1 ,data);
  return data[0];
}
 /**
  * @file   SHT2x_WriteUserRegister
  * @brief  writes the SHT2x user register (8bit)
  * @param  userdata£ºÒªÐ´µÄ²ÎÊý
  * @retval ENABLE£º³É¹¦£¬DISABLE£ºÊ§°Ü
  */
FunctionalState SHT2x_WriteUserRegister(unsigned char userdata)
{
	SHT2X_IIC_WriteByte(USER_REG_W ,userdata);
	if(userdata==SHT2x_ReadUserRegister())
	return ENABLE;
	else
	return DISABLE;
}

 /**
  * @file   SHT2x_Calc_T
  * @brief  ¼ÆËãÎÂ¶È
  * @param  NO
  * @retval ·µ»ØÎÂ¶ÈÖµ
  */
FunctionalState SHT2x_Calc_T(void)
{
	 unsigned char length=0;
		 uint8_t Tdata[3]={0};
		 if(!I2C_Start())return DISABLE;
	    I2C_SendByte(I2C_ADR_W); //128,   // sensor I2C address + write bit
	    if(!I2C_WaitAck())
			{I2C_Stop(); return DISABLE;}
	    I2C_SendByte(0xF3);     // 0xF3TRIG_T_MEASUREMENT_POLL
	    I2C_WaitAck();
			delay_us(20);
		  I2C_Stop();
			do
			{
			DELAY(100);
			I2C_Start();
	        I2C_SendByte(I2C_ADR_R);
			}
			while(!I2C_WaitAck());

		/*	for(length=0;length<=1;length++) //本来是3
			{
				Tdata[length]=I2C_ReceiveByte();
				printf("2\r\n");
				I2C_Ack();
			};
		*/
			Tdata[0]=I2C_ReceiveByte();
		//	printf("%c\r\n",Tdata[0]);
			I2C_Ack();
			Tdata[1]=I2C_ReceiveByte();
		//	printf("%c\r\n",Tdata[1]);

			I2C_NoAck();
			I2C_Stop();
	//		if(((Tdata[0]+Tdata[1]+Tdata[2])>0)&&SHT2x_CheckCrc(Tdata,0,2,Tdata[2]))
	   temperatureC= (-46.85 + (175.72/65536 )*((float)((((unsigned short)Tdata[0]<<8)+(unsigned short)Tdata[1])&0xfffc)));
	//		else       unsigned short
	//		return DISABLE;

		  return ENABLE;
};


 /**
  * @file   SHT2x_Calc_RH
  * @brief  ¼ÆËãÊª¶È
  * @param  NO
  * @retval ·µ»ØÊª¶ÈÖµ
  */
FunctionalState SHT2x_Calc_RH(void)
{
   unsigned char length=0;
   uint8_t RHdata[3]={0};
	 if(!I2C_Start())return DISABLE;
    I2C_SendByte(I2C_ADR_W);
    if(!I2C_WaitAck())
		{I2C_Stop(); return DISABLE;}
    I2C_SendByte(TRIG_RH_MEASUREMENT_POLL);
    I2C_WaitAck();
		delay_us(20);
	  I2C_Stop();
		do
		{
			DELAY(100);
		I2C_Start();
    I2C_SendByte(I2C_ADR_R);
		}
		while(!I2C_WaitAck());
		//for(length=0;length<=3;length++)
	//	{
		//	RHdata[length]=I2C_ReceiveByte();
	//		I2C_Ack();
	//	};
		RHdata[0]=I2C_ReceiveByte();
				//	printf("%c\r\n",Tdata[0]);
					I2C_Ack();
					RHdata[1]=I2C_ReceiveByte();
				//	printf("%c\r\n",Tdata[1]);
		I2C_NoAck();
		I2C_Stop();
	//	if(((RHdata[0]+RHdata[1]+RHdata[2])>0)&&SHT2x_CheckCrc(RHdata,0,2,RHdata[2]))
	  humidityRH = -6.0 + 125.0/65536 * ((float)((((unsigned short int)RHdata[0]<<8)+(unsigned short int)RHdata[1])&0xfff0));
	//	else
	//	return DISABLE;
	  return ENABLE;
}
 /**
  * @file   SHT2x_SoftReset
  * @brief  Èí¼þ¸´Î»
  * @param  NO
  * @retval NO
  */
FunctionalState SHT2x_SoftReset(void)
{
	 if(!I2C_Start())return DISABLE;
    I2C_SendByte(0x80);
    if(!I2C_WaitAck()){I2C_Stop(); return DISABLE;}
    I2C_SendByte(SOFT_RESET);
    I2C_WaitAck();
    I2C_Stop();
  	delay_ms(1500);
		return ENABLE;
}

 /**
  * @file   SHT2x_GetSerialNumber
  * @brief  µÃµ½SHT20µÄÐòÁÐºÅ
  * @param
  * @retval
  */
unsigned char SHT2x_GetSerialNumber(unsigned char *pBuffer1,unsigned char *pBuffer2)
{   unsigned char length=8;
	  if(!I2C_Start())return DISABLE;
    I2C_SendByte(0x80);
    if(!I2C_WaitAck()){I2C_Stop(); return DISABLE;}
    I2C_SendByte(0xfa);
    I2C_WaitAck();
    I2C_SendByte(0x0f);
    I2C_WaitAck();
		if(!I2C_Start())return DISABLE;
    I2C_SendByte(0x81);
    if(!I2C_WaitAck()){I2C_Stop(); return DISABLE;}
    while(length)
    {
      *pBuffer1 = I2C_ReceiveByte();
      if(length == 1)
				I2C_NoAck();
      else I2C_Ack();
      pBuffer1++;
      length--;
    }
     I2C_Stop();
		length=6;
	  if(!I2C_Start())return DISABLE;
    I2C_SendByte(0x80);
    if(!I2C_WaitAck()){I2C_Stop(); return DISABLE;}
    I2C_SendByte(0xfc);
    I2C_WaitAck();
    I2C_SendByte(0xc9);
    I2C_WaitAck();
		if(!I2C_Start())return DISABLE;
    I2C_SendByte(0x81);
    if(!I2C_WaitAck()){I2C_Stop(); return DISABLE;}
    while(length)
    {
      *pBuffer2 = I2C_ReceiveByte();
      if(length == 1)
				I2C_NoAck();
      else I2C_Ack();
      pBuffer2++;
      length--;
    }
     I2C_Stop();
    return ENABLE;
}
 /**
  * @file   SHT2X_Init
  * @brief  SHT20³õÊ¼»¯
  * @param  NO
  * @retval NO
  */

/*********************************************************************************************************
      END FILE
*********************************************************************************************************/

// Program flow
// 1. Configure I2C as master (requires external connections with I2C on the slave board, don't forget the external pull-ups.
// 2. Prompt the user to type a character ('0', '1', or '2') then [Return]
// 3. Transmit the character to the slave board's I2C address to put the slave to sleep.
// 4. Prompt the user to type [Esc] to proceed with waking up the slave.
// 5. Transmit the slave board's address to wake up the slave.
//自配的
int main(void) {

  // Configure the debug uart (see Serial.c)
  setup_debug_uart();
  I2C_GPIO_Config();


  while(1) {

	//	if(SHT2x_WriteUserRegister(0x3a))
	//	printf("OK\r\n");
	//	else
	//	printf("error\r\n");
	  if(SHT2x_Calc_T())//SHT2x_Calc_T()
	  	  		{

	  	  		//	printf("OK\r\n");
	  	  			printf("%f\r\n",temperatureC);
	  	  		    //OLED_shuji(38,17,(s8)(temperatureC));
	  	  		//delay_ms(1000);
	  	  	    /*Êª¶È²âÊÔ*/


	  	  		}
	  if(SHT2x_Calc_RH())
	  	  	  			{
	  	  	  				printf("%f\r\n",humidityRH);
	  	  	  			DELAY(20000);
	  	  	  			}

/////	  SHT2x_SoftReset();
	  //	 	else
	  	 //		printf("error\r\n");

  } // end of while(1)

}  // end of main
